package com.yqg.protection.controller.dataHandler;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yqg.protection.entity.*;
import com.yqg.protection.listenern.NoticeWebsocket;
import com.yqg.protection.mapper.UserMapper;
import com.yqg.protection.service.IEquipmentInputStoreService;
import com.yqg.protection.service.IFireSysDataService;
import com.yqg.protection.service.IOrganizationService;
import com.yqg.protection.service.ITemporaryDataService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

/**
 * projectName:xf-service
 * author:zxf
 * time:2025/8/30 17:12
 * description:
 */
@Component
public class ProtocolUtil {

    @Resource
    private IEquipmentInputStoreService equipmentInputStoreService;

    @Resource
    private UserMapper userMapper;

    @Resource
    private IOrganizationService organizationService;

    @Resource
    private NoticeWebsocket noticeWebsocket;

    @Resource
    private IFireSysDataService fireSysDataService;

    @Resource
    ITemporaryDataService temporaryDataService;

    // 获取设备对象
    public EquipmentInputStore getEquipmentInputStore(String deviceId) {
        LambdaQueryWrapper<EquipmentInputStore> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EquipmentInputStore::getEquipmentId, deviceId);
        queryWrapper.eq(EquipmentInputStore::getIsDelete, 0);
        return equipmentInputStoreService.getOne(queryWrapper);
    }

    // 记录设备数据上传内容
    public void saveFireSysData(String deviceId, String explanation, String enterTime) {
        FireSysData fireSysData = new FireSysData();
        fireSysData.setEquipmentId(deviceId);
        fireSysData.setExplanation(explanation);
        fireSysData.setEnterTime(enterTime);
        fireSysDataService.save(fireSysData);
    }

    // 更新设备数据上传时间(用于记录设备是否在线)
    public void updateTemporaryData(String deviceId, String sendTime) {
        LambdaQueryWrapper<TemporaryData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TemporaryData::getEquipmentId, deviceId);
        TemporaryData temporaryData = temporaryDataService.getOne(queryWrapper);

        if (temporaryData == null) {
            temporaryData = new TemporaryData();
            temporaryData.setEquipmentId(deviceId);
        }
        temporaryData.setUpTime(LocalDateTime.parse(sendTime.replace(" ", "T")));
        temporaryDataService.saveOrUpdate(temporaryData);
    }

    //报警推送
    public void sendWarnNotice(EquipmentInputStore equipmentInputStore, List<WarnRecord> warnRecords) {
        Set<Long> sendUserIds = noticeWebsocket.conns.keySet();
        if (warnRecords.size() > 0 && sendUserIds.size() > 0) {
            Organization organization = organizationService.getById(equipmentInputStore.getOrganization());
            List<Long> userIds = userMapper.getonlineUsersByOrganId(organization.getLevel(), organization.getCountry(),
                    organization.getScTeam(), organization.getFcTeam(),
                    organization.getFbTeam(), organization.getCommunity(),
                    organization.getBuilding(), organization.getUnit(),
                    organization.getFloor(), organization.getRoom(),
                    sendUserIds, equipmentInputStore.getClientId());

            HashMap<String, Object> noticeInfo = new HashMap<>();
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < warnRecords.size(); i++) {
                WarnRecord warnRecord = warnRecords.get(i);
                if (warnRecord.getPartModel() != null && !"".equals(warnRecord.getPartModel())) {
                    stringBuilder.append(warnRecord.getWarnAddr() + warnRecord.getPartModel() + "部件" + (warnRecord.getWarnStateNum().equals("1") ? "报警" : "故障"));
                } else {
                    stringBuilder.append(warnRecord.getWarnAddr() + equipmentInputStore.getEquipmentName() + "设备" + (warnRecord.getWarnStateNum().equals("1") ? "报警" : "故障"));
                }
            }
            noticeInfo.put("type", "video");
            noticeInfo.put("msg", stringBuilder);
            for (Long userId : userIds) {
                noticeWebsocket.sendMessageByUserId(userId, noticeInfo);
            }
        }
    }

}
